|
|
|||
|
|
Click Here! |
|
|
|
Chapter 20CGI and VBScriptby Ramesh Chandak
The very first Web pages lacked interactivity. Users could only browse through them and use hyperlinks to jump from one page to another. Common Gateway Interface (CGI) is one of several ways you can use to add interactivity to your Web pages. Other methods include using Java, JavaScript, VBScript, ActiveX, and plug-ins. CGI represents a simple protocol of communication between the Web forms and the programs that reside on the Web server. A CGI script or program gets its input from the Web forms, processes it, and sends the results back to your browser. CGI is not a programming language; it is a script or a program that resides on the server. You can create a CGI script or program using almost any programming language, such as C/C++, Visual Basic, Perl, FORTRAN, or AppleScript, that supports standard input and output processing. This chapter introduces you to the concept of CGI, discusses why CGI was invented, and explains the different CGI environment variables. It also discusses the basic architecture of a CGI-based Web application and how data is communicated in such an architecture. This chapter further discusses the process of building a CGI application and how you can use VBScript to perform certain processing on the client side thus eliminating the need for CGI scripts or programs for some common tasks. The CGI programs should process data and respond quickly. Remember, CGI programs get their input from the Web forms. The user is awaiting response while the data is being processed. Therefore, the CGI programs must respond quickly. Because the CGI programs reside on the server, you benefit from the server's processing power. Early on during the design of your project consider the following two points:
Understanding CGIThe best way to understand CGI and what it does comes from examples. The following example demonstrates the results obtained using CGI and without CGI. In this example, an order form is created and placed online to enable customers to order products from anywhere in the world. Listing 20.1 shows the HTML code that uses the mailto: command to send the order information from the browser to the Web server when the customer clicks the Send button. The company, product, and price information included in Listing 20.1 is fictitious and exists for demonstration purposes. Notice the following line in Listing 20.1: <FORM method=POST ACTION="mailto:xyz@rksoftware.com"> The preceding line indicates to the browser the information being sent to the specified e-mail address when the user clicks the Send button using the mailto: command. Figure 20.1 shows part of the HTML page resulting from Listing 20.1. Figure 20.1 : HTML page created using Listing 20.2's code. Listing 20.1. HTML sample using the mailto: command for ordering software.
Listing 20.2 shows the results obtained by using the mailto: command. Listing 20.2 Results obtained by using the mailto: command. Subject: Form posted from AIR Mosaic Content-type: application/x-www-form-urlencoded Content-length: 567 X-Mailer: AIR Mosaic (16-bit) version 1.00.198.07 WebFormID=2&Referred_by=&programs_ordered=My%20Software%20Lite%20%0D%0ACD-ROM- %20%2499&Country=&Zip/Postal_Code:=&State_or_Province=&City_or_town=&Address_ (line_2)=&Address_(line_1)=&Name=&email=&fax=&Telephone=&Ship_To_Country=USA&Ship_To_Zip/ Postal_Code=45632&Ship_To_State/Province=FL&Ship_To_City=Bonnesville&Ship_To_ Addr_(line_2)=&Ship_To_Addr_(line_1)=456%20Whatever%20Street&Company_ Name=XYZ%20Corporation&Ship_To_Name=XYZ%20Corporation&Expiration=9%2f99&Credit_ Card_Number=1234567890123456&card_type=VISA&Subject=Software%20Order&recipient= xyz@rksoftware.com As you can see, the e-mail received using the mailto: command is not easily readable. It needs to be parsed before you can decipher what it contains. A CGI script or program comes in handy here because a CGI script would parse the message into a readable format before it is sent. Listing 20.3 shows the HTML code that uses a CGI script to send the same order information from the browser to the Web server. Notice the following line in Listing 20.3: <FORM method=POST ACTION="http://www.rksoft.net/cgi-bin/formmail.pl"> The preceding line invokes the CGI script, formmail.pl, written in Perl and residing on the Web server in the cgi-bin directory. Listing 20.3. HTML sample using CGI for ordering software.
Listing 20.4 shows the results obtained by using a CGI script. Listing 20.4. Results obtained by using a CGI script. Subject: Form posted from AIR Mosaic Content-type: application/x-www-form-urlencoded Content-length: 567 X-Mailer: AIR Mosaic (16-bit) version 1.00.198.07 WebFormID=2 Referred_by= programs_ordered=My Software Lite CD-ROM Country= Zip/Postal_Code:= State_or_Province= City_or_town= Address_(line_2)= Address_(line_1)= Name= email= fax= Telephone= Ship_To_Country=USA Ship_To_Zip/Postal_Code=45632 Ship_To_State/Province=FL Ship_To_City=Bonnesville Ship_To_Addr_(line_2)= Ship_To_Addr_(line_1)=456 Whatever Street Company_Name=XYZ Corporation Ship_To_Name=XYZ Corporation Expiration=9/99 Credit_Card_Number=1234567890123456 card_type=VISA Subject=Software Order recipient=xyz@rksoftware.com This result appears much more readable! The CGI script included in Listing 20.4 processes the data received from the Web form and e-mails it to you in a meaningful form. You receive the customer order as simple ASCII text that is easily readable. CGI scripting performs this kind of task and much more. CGI scripts help connect your Web site to a relational database, which enables visitors and customers to easily browse and search your product catalog. Airlines can set up sites that let their customers inquire about flight schedules and make reservations online. Banks can set up Web sites that enable their customers to check balances and make transfers. Libraries can set up sites that enable readers to search for books and magazines. A CGI program can send data back to the browser, making the communication a two-way traffic. CGI is not a programming language. It represents a simple communication protocol that establishes the communication layer between the server and the server-side applications. Figure 20.2 shows the architecture of a CGI-based Web application. Figure 20.2 : Architecture of a CGI application. A CGI program is nothing but a simple application that accepts input, processes it, and sends the resulting output to its appropriate destination. Therefore, you can use any standard programming or scripting language that supports input/output processing to write your CGI programs. Potential candidates include C/C++, Visual Basic, Perl, or FORTRAN. If you use C/C++ or Visual Basic, you create a CGI program. A CGI program is an executable, similar to the executables you create for your desktop client/server applications. If you use a scripting language such as Perl or AppleScript, you create a CGI script. You will find it easier to create and maintain a script. Any changes made to a program must undergo the compile, link, and build process before the program can be executed. Whether you choose to create a program or script depends on the tool you plan to use. The choice of tool depends on your familiarity with the tool and its programming syntax and structure. If you programmed with C/C++ all your life, you may feel better using C/C++ to write your CGI programs. In fact, you may be able to reuse your library of C/C++ routines for some of your CGI programs. On the other hand, if you are an avid Visual Basic developer, you probably want to continue using it to write your CGI programs. CGI programs reside on the server. They benefit from faster and better processing power of the server. The more powerful the server, the better execution and response time you get from your CGI programs. At the same time, you should pay special attention when writing your CGI program code. The code should be efficient and fast. In the preceding example, if the CGI program takes a long time to convert the order form data into simple ASCII, you would get all your e-mail notifications late. Your ability to process the orders on a timely basis would suffer. The standard programming rules to write clean, modular, and efficient code also apply to CGI programming. CGI SpecificationThe CGI specification came from Rob McCool of Netscape Communications. At the moment, the specification is under the supervision of the World Wide Web Consortium (W3C-http://www.w3.org).
The CGI specification enables you to expand the capabilities of
your server. It serves as a gateway between the Web server and
other server processes including databases.
The Web server captures the HTML form data into environment variables. A CGI script reads the environment variables, processes the data, and sends the response back to the browser. The form data is received as a set of name-value pairs. These pairs are separated by the & sign. The name and value tags are separated by the = sign. Because each name=value pair is URL encoded, the following conversion must occur:
The form data gets stored in the environment variable QUERY_STRING if the GET method is used in the FORM tag for submission. If the POST method is used in the FORM tag for submission, the form data is not stored in any environment variables. You get it from STDIN. Because the server does not send an EOF at the end of the data, use the environment variable CONTENT_LENGTH to determine the number of bytes to be read. The next section, "CGI Environment Variables," outlines the different variables available for storing and processing data. A number of scripts exist on the World Wide Web that do the preceding conversion. These scripts come in a number of different languages, including the Bourne Shell, C, Perl, Perl5, TCL, and many more. You can send different types of data back to the browser including HTML, GIF, and other MIME Content-Types. For example, to send HTML data, use the Content-Type of text/html. To send a GIF image, use the Content-Type of image/gif.
The Win-CGI standard is a CGI standard supported by some Windows-based
Web servers.
If you write CGI programs (executables, for example), the executables usually appear in the \cgi-bin\ directory on the server and the source code is stored in the \cgi-src\ directory. Security measures must exist to control access to both these directories. If you write CGI scripts, they usually get stored in the \cgi-bin\ directory. Because the script is its own source, you don't need to store anything in the \cgi-src\ directory. Again, security measures must exist to control access to the \cgi-bin\ directory-especially in this case, because the script is the source code itself. CGI Environment VariablesThe following CGI environment variables are set for all requests:
The following environment variables are specific to the request being fulfilled by the gateway program:
Architecture of a CGI ApplicationIn order to pass data about the information request from the server to the script, the server uses command-line arguments, as well as environment variables. These environment variables get set when the server executes the gateway program. Figure 20.2 describes the World Wide Web architecture of which CGI is one part. The Web browser is the client and it can interact with other applications such as Microsoft Word, Microsoft Excel, and Microsoft PowerPoint, depending on the nature of the application. The client connects to the Web server via the network. Several applications can reside on the server. The CGI interface acts as the gateway between the Web server and the server-side processes. One of the server-side processes could be a relational database. Although CGI acts as a gateway between any type of Web server and server-side applications, it has been more commonly implemented with the HTTPd server. The client browser invokes the CGI script and waits until the CGI script completes its process. Thus, the CGI script must execute fast enough to have no perceived delay in the response time. The drawback of using CGI is that every time a CGI script is invoked, the Web server spawns a new process. This setup becomes a problem when a given Web site gets frequently accessed by several users. It results in the Web server spawning a plethora of processes. In the previous example, the CGI script processes the form order and notifies the company about receiving a customer order. You can extend the script further to dial into a credit card bureau and check the validity of the credit card number provided by the customer. The script can notify the customer about the acceptance or denial of the order. If the order gets accepted, the customer receives an order reference number. If the order is not accepted, the denial reasons are indicated. CGI Versus VBScriptCertain tasks exist that could be easily performed on the client side with VBScript, thus avoiding the use of CGI programs. For example, processing mouse clicks and validating user input, come to mind. Consider the example of validating user input on the client side itself before the data goes to the server. Validating user input before it goes to the server represents good programming practice because the server's processing power can be better utilized for other important tasks.
Not everything can be implemented using VBScript. In some cases,
you still need to consider CGI as a possible option for your application.
For example, if your application needs to communicate with a back-end
database, CGI provides one way to implement it, whereas VBScript
doesn't work for such tasks. Whether you use VBScript or CGI,
or both, depends on the nature of your application, as well as
your familiarity with VBScript and CGI.
ExamplesThis section reviews and analyzes a VBScript example downloaded from the Web site http://www.microsoft.com/vbscript. Figure 20.3 shows a simple Web page created by the HTML code included in the file msftd.html on the companion CD-ROM. This HTML displays an order form that enables you to place orders for flowers. You specify the occasion and enter the name and address where the flowers should be sent. Figure 20.3 : Ordering flowers Web page created using HTML and VBScript. Look at the code part by part. Listing 20.5 represents all the HTML code used to set up the form. Three radio buttons are displayed so the user can select Birthday (default), Anniversary, or Get well soon. These buttons are displayed using the <Input Type> tag. This part of the code remains the same no matter whether you use CGI or VBScript. Next, you add the data-entry fields for entering name and address of the destination. The <Input> tag is used to add these fields. Three buttons-Submit, Clear, and Init-are added at the bottom. The Submit button sends the order. The Clear button clears the name and address fields. The Init button initializes the data-entry fields. If you use CGI scripts to process user input and mouse clicks, you would include reference to those scripts in your HTML code. For example, the Submit button would include a reference to a CGI script residing on the server. This script is invoked when the user clicks the Submit button. The mouse click gets processed on the server and the results are transmitted back to the browser. This process becomes expensive because every such event would be processed on the server. It also increases network traffic and loads the server with trivial tasks that could easily be processed on the client side. Consequently, you have a very inefficient use of the server and its processing power. Listing 20.5. HTML code for setting up the form for ordering flowers. <HEAD><TITLE>VBScript sample: Ordering Flowers</TITLE></HEAD> <BODY> <TABLE WIDTH="80%"> <TR VALIGN=bottom> <TD WIDTH="40%"><IMG SRC="/vbscript/us/vbssamp/msftd/ msftd.gif" ALIGN=center></TD> <TD WIDTH="60%"><FONT SIZE=12><I>Order Flowers </I></FONT></TD> </TR> </TABLE> <FONT FACE="Times New Roman" SIZE=4>What is the occasion? </FONT><BR> <PRE> <INPUT TYPE=RADIO NAME=OptOccasion CHECKED> Birthday <INPUT TYPE=RADIO NAME=OptOccasion> Anniversary <INPUT TYPE=RADIO NAME=OptOccasion> Get well soon </PRE> <FONT FACE="Times New Roman" SIZE=4>When and where should the flowers be sent? </FONT><BR> <PRE> Date <INPUT NAME=TxtDate SIZE=60> Name <INPUT NAME=TxtName SIZE=60> Address <INPUT NAME=TxtAddress SIZE=60> City <INPUT NAME=TxtCity SIZE=60> State <INPUT NAME=TxtState SIZE=60> Zip code <INPUT NAME=TxtZip SIZE=60> <INPUT TYPE=BUTTON VALUE="Submit" NAME="BtnSubmit"> <INPUT TYPE=BUTTON VALUE="Clear" NAME="BtnClear"> <INPUT TYPE=BUTTON VALUE="Init" NAME="BtnInit"><BR> </PRE> Listing 20.6 shows the VBScript code used to process the data entered by the user. This code also processes the mouse click events when the user clicks the Submit, Clear, or Init buttons. Prior to JavaScript and VBScript, such processing would occur on the server using CGI programs and scripts. VBScript extends the HTML code and validates user input before it is sent to the server. This setup reduces network traffic, decreases server load, and improves the overall performance of your Web page. Two variants and six procedures get defined: strMsgBoxTitle and bValidOrder and Window_OnLoad, BtnInit_OnClick, BtnSubmit_OnClick, ValidateDeliveryDate, CheckSpecified, and BtnClear_OnClick. The subroutine Window_OnLoad gets executed when the Web page window is first loaded by the browser. It assigns the value MSFID to the variant strMsgBoxTitle. The variant StrMsgBoxTitle is assigned a string value; therefore, it is now a string variable. The strMsgBoxTitle is used to display the title for the message box. Next the subroutine Window_OnLoad calls the BtnInit_OnClick procedure. This procedure initializes the data-entry fields. The procedure BtnInit_OnClick initializes the data-entry fields. It is executed when the Web page window is first loaded. It also gets executed when the user clicks the Init button. The procedure BtnSubmit_OnClick gets executed when the user clicks the Submit button. It checks to make sure if the data entered is valid. If it is valid, the variable bValidOrder is initialized to true at the beginning of this procedure and retains its initialized value. If bValidOrder is true, the order gets sent. If the data entered is invalid, bValidOrder is set to false and the control is returned to the user on the Web page. The procedure ValidDeliveryDate determines whether the value specified in the date field is valid. The procedure CheckSpecified is actually called by the BtnSubmit_OnClick procedure. It determines whether the data entered in name and address fields is valid. The procedure BtnClear_OnClick is executed when the user clicks the Clear button. It clears the data-entry fields. Listing 20.6. VBScript code for processing mouse clicks and user input.
The remaining part of the code is again all HTML. It remains the same no matter whether you use CGI or VBScript. In this example, all the VBScript code is encapsulated between the <SCRIPT> and </SCRIPT> tags. The entire code resides in a single location within the body of the HTML code, making the code modular and easy to locate. The VBScript code is listed in the <BODY> section of the HTML code. Relevant Web Sites
Table 20.1 lists few Web sites for more information on CGI and
VBScript. Plenty of resources and examples exist on the Internet.
ReviewCGI represents a simple protocol of communication between the Web forms and your programs that reside on the Web server. A CGI script or program gets its input from the Web forms, processes it, and sends the results back to your browser. CGI is not a programming language; it is a script or a program that resides on the server. You can create a CGI script or program using almost any programming language that supports standard input and output processing. For example, you can use C/C++, Visual Basic, Perl, or FORTRAN to write your CGI programs. The best language to use is the one that you feel familiar with and comfortable using. Whatever you choose, make sure your CGI programs process data efficiently and respond quickly. Remember, CGI programs get their input from the Web forms, and the user waits for the response while the data is being processed. Therefore, the CGI programs need to respond quickly. You have two important decisions to make about CGI early on for your project. First, decide whether your project demands the use of CGI. Then, you have to decide how to protect the CGI programs. Because a CGI program is invoked as a result of user action through the browser, you need to undertake necessary security precautions. The CGI programs should be under direct control of the Webmaster only and all others should have only execute rights. VBScript programming is simpler than CGI programming. This chapter introduced CGI and explained the different CGI environment variables. It compared CGI with VBScript and identified how VBScript can be used to handle some of the processing on the client side, thus eliminating or reducing the need for CGI scripts and reducing the load on the network and server. Data communication in a CGI-based web architecture was also discussed. This chapter also included examples of VBScript code for processing mouse clicks and user input. There is plenty of resources and examples available on the Net. A list of few relevant and useful web sites is included in this chapter. Be sure to visit the Microsoft VBScript site regularly to keep abreast of the latest on Microsoft Internet Explorer and VBScript. VBScript is the new kid on the block and it is expected to grow and evolve over time. If you use CGI scripts to process user input and mouse clicks, you load the server with many trivial tasks that could very easily be handled on the client side. You also increase network traffic. This setup creates an inefficient use of the server and its processing power. Using VBScript to handle such tasks reduces network traffic and server load. |
|
|
|
|
Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details. |